'use strict';

const Controller = require('egg').Controller;

class User_bookletController extends Controller {
  //创建记录
  async create() {
    const { ctx, service } = this;
    const { Response, ResponseError, request: {body} } = ctx
    const res = new Response() //作为响应
    try {
      let { recordStart, recordEnd, user_id } = body
      const user = await service.user.find(user_id)
      if(!user) throw new ResponseError('用户不存在，无法分配书籍') //用户不存在

      let distributeBookletCount = 0
      recordEnd = recordEnd || recordStart //如果没有传递recordEnd
      for( let i=recordStart; i<=recordEnd; i++ ) { // 遍历导入书籍编号
        const booklet = await service.booklet.find(i)
        const booklet_id = booklet.id
        if(booklet) {//是否有该id的书
          const userBookletRecord = await service.userBooklet.findByFields({booklet_id, user_id})
          if(userBookletRecord && userBookletRecord.status === '0') {
            userBookletRecord.status = '1'
            await userBookletRecord.save()
          }else if(userBookletRecord && userBookletRecord.status === '1') {
            continue //throw new ResponseError('该书本已经分配')
          }else {
            await service.userBooklet.create({
              user_id, booklet_id
            })
            distributeBookletCount++
          }
        }else { //没有这本书
          continue
        }
      }
      res.message = distributeBookletCount +'本书籍分配完成'
    }catch(e) {
      console.log(e.message)
      res.status = ctx.STATUS.ERROR;
			res.message = e;
    }
    ctx.body = res
  }

  //删除用户书籍
  async softDestroy() {
    const { ctx, service } = this;
    const { Response, ResponseError, params, request: { body } } = ctx
    const res = new Response() //作为响应
    try {
      let destroyBookletCount = 0 //删除的书籍
      const { user_id } = params
      const user = await service.user.find(user_id)
      if(!user) throw new ResponseError('用户不存在，无法删除书籍') //用户不存在

      let { recordStart, recordEnd } = body
      recordEnd = recordEnd || recordStart //如果没有传递recordEnd
      for( let i=recordStart; i<=recordEnd; i++ ) { // 遍历导入书籍编号
        const booklet_id = i
        const userBookletRecord = await service.userBooklet.findByFields({booklet_id, user_id})
        if(userBookletRecord && userBookletRecord.status === '0') {
          continue //该书本身就被删除
        }else if(userBookletRecord && userBookletRecord.status === '1') {
          userBookletRecord.status = '0'
          await userBookletRecord.save()
          destroyBookletCount++
        }else {
          continue //该书不存在 说明booklet_id有误
        }
      }
      // await service.user.softDestroy(user_id) 不知道为什么需要这一行
      res.message = destroyBookletCount + '本被删除成功'
    }catch(e) {
      console.log(e.message)
      res.status = ctx.STATUS.ERROR;
			res.message = e;
    }
    ctx.body = res
  }
}

module.exports = User_bookletController;
